package base.utils;

import java.lang.reflect.Field;

import org.json.JSONObject;

import com.google.gson.Gson;

public class GsonUtils {

	private static final String TAG = GsonUtils.class.getSimpleName();

	/**
	 * Convert json to classOfT
	 * 
	 * @param json
	 * @param classOfT
	 * @return
	 */
	public static <T> T convert(JSONObject json, Class<T> classOfT) {
		if (json == null || json.length() <= 0) {
			return null;
		}
		Gson gson = new Gson();
		return gson.fromJson(json.toString(), classOfT);
	}

	/**
	 * 
	 * Convert json and set value to objToSet.
	 * 
	 * @param json
	 * @param objToSet
	 */
	public static void convert(JSONObject json, Object objToSet) {
		if (json == null || json.length() <= 0 || objToSet == null) {
			return;
		}
		copy(convert(json, objToSet.getClass()), objToSet);
	}

	/**
	 * 
	 * 
	 * @param from
	 * @param to
	 */
	public static void copy(Object from, Object to) {
		// Logger.debug(TAG, "copy from -> "+from +" to -> "+to);
		try {
			Field[] field = from.getClass().getDeclaredFields();
			for (int i = 0; i < field.length; i++) {
				try {
					Field f = field[i];
					f.setAccessible(true);
					f.set(to, f.get(from));
					f.setAccessible(false);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			Logger.error(TAG, "");
		}
	}

}
